package com.baiyu.common.utils;

import com.aliyuncs.utils.SslUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.util.Base64Utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;

public class PictureUtils {

    /**
     * 将网络路径图片转为base64的格式
     * @param requestUrl 请求网络路径
     * @param photoType 响应的格式(png,jpg,ico等)
     * @throws Exception
     */
//    public static String getUrlImageToBase64(String requestUrl, String photoType) throws Exception {
//        ByteArrayOutputStream data = new ByteArrayOutputStream();
//        try {
//            // 创建URL
//            URL url = new URL(requestUrl);
//            byte[] by = new byte[1024];
//
//            // 创建链接
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            conn.setRequestMethod("GET");
//            conn.setConnectTimeout(5 * 1000);
//            InputStream is = conn.getInputStream();
//
//            // 将内容读取内存中
//            int len = -1;
//            while ((len = is.read(by)) != -1) {
//                data.write(by, 0, len);
//            }
//
//            // 关闭流
//            is.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        // 对字节数组Base64编码
//        Base64.Encoder encoder = Base64.getEncoder();
//        return "data:image/" + photoType + ";base64," + encoder.encodeToString(data.toByteArray());
//    }

    /**
     * 服务器图片转换base64 path：服务器图片路径  返回 base64编码（String 类型）
     * @param path
     * @return
     */
    public String imgToBase64(String path){
        String str = "";
        path = path.replaceAll("http://", "https://");

        try{
            BufferedImage image = getImageFromUrl(path);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", stream);
            str= Base64Utils.encodeToString(stream.toByteArray());
        }catch (Exception e){
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 图片来源于url
     * @param url
     * @return
     */
    static BufferedImage getImageFromUrl(String url){
        BufferedImage bi = null;
        try {
            // 读取源图像
            URL bgPicUrl = new URL(url);
//            InputStream inStream = getInputStreamByUrl(url);
//            byte[] bytes = HttpsUtils.getBytes(url);
//            InputStream buffin = new ByteArrayInputStream(bytes,0,bytes.length);
//            BufferedImage img = null;
//            img = ImageIO.read(buffin);
//            return img;
            bi = ImageIO.read(bgPicUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bi;
    }

    /**
     * 根据url地址 获取输入流
     * @param
     * @return
     * @throws IOException
     */
    private InputStream getInputStreamByUrl(String urlPath) throws IOException {
        InputStream is = null;
        File file = null;
        try {
            // 统一资源
            URL url = new URL(urlPath);
            if("https".equalsIgnoreCase(url.getProtocol())){
                SslUtils.ignoreSsl();
            }
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000 * 5);
            //设置请求方式，默认是GET
            httpURLConnection.setRequestMethod("GET");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();
            // 文件大小
            int fileLength = httpURLConnection.getContentLength();

            // 控制台打印文件大小
            System.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");

            // 建立链接从请求中获取数据
            URLConnection con = url.openConnection();
            is = new BufferedInputStream(httpURLConnection.getInputStream());
        }catch (Exception e){
            e.getMessage();
        }
        return is;
    }

    public String getBase64Str() throws Exception{
        // 获取图片流
        HttpGet httpGet = new HttpGet("图片url");
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();

        // 从流中获取数据
        byte[] data = new byte[(int) entity.getContentLength()];
        int offset = 0;
        int readBytes = 0;
        do {
            readBytes = inputStream.read(data, offset, 2048);
            offset += readBytes;
        } while (readBytes != -1);

        // Base64 编码
        Base64.Encoder encoder = Base64.getEncoder();
        String result = encoder.encodeToString(data);
        System.out.println(result);

        // 关闭资源
        response.close();
        httpClient.close();

        return result;
    }
}
